package org.ricks.log;

import java.io.File;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author chenwei
 * @Title:
 * @Package
 * @Description:
 * @date 2021/2/110:49
 */
public final class DailyPolicy implements Policy {

    /* Regular expression for a time with hours and optional minutes */
    private static final Pattern TIME_PATTERN = Pattern.compile("^([01]?[0-9]|2[0-3])([^\\d]+([0-5]?[0-9]))?$");

    private static final int GROUP_HOUR = 1;
    private static final int GROUP_MINUTE = 3;

    private final Calendar calendar;

    /** */
    public DailyPolicy() {
        this(null);
    }

    /**
     * @param argument
     *            Time for starting new log file (e.g. "23:30")
     */
    public DailyPolicy(final String argument) {
        calendar = Calendar.getInstance();
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        if (argument == null || argument.isEmpty()) {
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
        } else {
            Matcher matcher = TIME_PATTERN.matcher(argument);
            if (matcher.matches()) {
                String hour = matcher.group(GROUP_HOUR);
                String minute = matcher.group(GROUP_MINUTE);
                calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour));
                calendar.set(Calendar.MINUTE, minute == null ? 0 : Integer.parseInt(minute));
            } else {
                throw new IllegalArgumentException("Invalid time for daily policy: " + argument);
            }
        }

        reset();
    }

    @Override
    public boolean continueExistingFile(final String path) {
        Calendar clone = (Calendar) calendar.clone();
        clone.add(Calendar.DATE, -1);
        return clone.getTimeInMillis() <= new File(path).lastModified();
    }

    @Override
    public boolean continueCurrentFile(final byte[] entry) {
        return calendar.getTimeInMillis() > System.currentTimeMillis();
    }

    @Override
    public void reset() {
        while (calendar.getTimeInMillis() <= System.currentTimeMillis()) {
            calendar.add(Calendar.DATE, 1);
        }
    }

}
